//
//  BaseViewController.m
//  Training
//
//  Created by michael shen on 15/6/15.
//  Copyright (c) 2015年 coolem. All rights reserved.
//

#import "BaseViewController.h"
//#import "HttpToolAction.h"

@interface BaseViewController (){
    int angle;
}

@property (strong,nonatomic) MBProgressHUD *waitingView;
@property (nonatomic) WaitingViewShowStyle viewStyle;
@property (nonatomic,strong) UIView *resultView;
@property (nonatomic,strong) UIView *showView;
@property (nonatomic,strong) UIImageView *showImageView;


@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //    if (self.viewNewStyle == localStyle) {
    //        self.view.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0f];
    //        if (IOS7_OR_LATER) {
    //            self.edgesForExtendedLayout = UIRectEdgeNone;
    //            self.extendedLayoutIncludesOpaqueBars = YES;
    //            self.automaticallyAdjustsScrollViewInsets = NO;
    //
    //
    //        }
    //        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    //        backItem.title = @"返回";
    //        self.navigationItem.backBarButtonItem = backItem;
    //        self.view.multipleTouchEnabled = NO;
    //        NSLog(@"%@",self.navigationController.viewControllers);
    //    }else{
    //
    //    }
    if (IOS7_OR_LATER) {
        //        self.edgesForExtendedLayout = UIRectEdgeNone;
        //        self.extendedLayoutIncludesOpaqueBars = YES;
        self.automaticallyAdjustsScrollViewInsets = NO;
        
    }
    self.view.backgroundColor = HexRGB(0xf5f5f5);
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"";
    //    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    //    [self.view addSubview:view];
    //    backItem.image = [UIImage imageNamed:@"back"];
    
    //backItem.title = @"返回";
    //    backItem.image = [UIImage imageNamed:@"icon_back"];
    //    UIImage *image = [UIImage imageNamed:@"icon_back"];
    //    [backItem setBackButtonBackgroundImage:[image resizableImageWithCapInsets:UIEdgeInsetsMake(0, -image.size.width, 0, 0)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    //    [backItem setBackButtonTitlePositionAdjustment:UIOffsetMake(-400.f, 0)];
    //    [backItem setBackButtonBackgroundVerticalPositionAdjustment:<#(CGFloat)#> forBarMetrics:<#(UIBarMetrics)#>];
    self.navigationItem.backBarButtonItem = backItem;
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];

    
    //    self.navigationItem.backBarButtonItem.imageInsets = UIEdgeInsetsMake(0, -20, 0, 20);
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //    self.navigationController.navigationBarHidden = NO;
    //    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    //    view.backgroundColor = [UIColor whiteColor];
    //    [self.view addSubview:view];
    
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //    if (self.navigationController.viewControllers.count>1) {
    //        self.navigationController.navigationBarHidden = YES;
    //
    //    }
    
    
    
}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    //    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    //        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    //    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) startAnimation
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.01];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(endAnimation)];
    //    self.showImageView.transform = CGAffineTransformMakeRotation(angle * (M_PI / 180.0f));
    self.showImageView.layer.transform=CATransform3DMakeRotation(angle * (M_PI / 180.0f), 0, 1, 0);
    
    [UIView commitAnimations];
}

-(void)endAnimation
{
    angle += 10;
    [self startAnimation];
}

-(void)showMessageWithMigrantView{
    self.showView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _showView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_showView];
    NSMutableArray *rotateArray = [[NSMutableArray alloc] init];
    for (int i =0; i<50; i++) {
        [rotateArray addObject:[UIImage imageNamed:[NSString stringWithFormat:@"rotate_%d",i]]];
    }
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-50, (SCREEN_HEIGHT/2)-50, 100, 100)];
    imageView.image = [UIImage imageNamed:@"rotate_0"];
    imageView.animationImages = rotateArray;
    imageView.animationRepeatCount = 0;
    imageView.animationDuration = 1.0;//设置动画时间
    [self.showView addSubview:imageView];
    [imageView startAnimating];
    
    //    self.showImageView = imageView;
    //    angle = 10;
    //    [self startAnimation];
    //    [UIView animateWithDuration:0.01
    //                          delay:0
    //                        options:UIViewAnimationOptionRepeat
    //                     animations:^{
    //                         imageView.layer.transform=CATransform3DMakeRotation(M_PI, 0, 1, 0);
    //                     }
    //                     completion:^(BOOL finished) {
    //                         imageView.layer.transform=CATransform3DMakeRotation(M_PI, 0, 1, 0);
    //                     }];
    
}

-(void)dismissMigrantView{
    [UIView animateWithDuration:0.5 animations:^{
        self.showView.alpha = 0;
    } completion:^(BOOL finished) {
        if (finished) {
            [self.showView removeFromSuperview];
            self.showView = nil;
        }
    }];
    
}

- (void)showMessage:(NSString *)message autoDissmissAfterDelay:(NSTimeInterval)interval{
    [self showMessage:message autoDissmissAfterDelay:interval finish:nil];
}

- (void)showMessage:(NSString *)message autoDissmissAfterDelay:(NSTimeInterval)interval finish:(void (^)())finish{
    [self showMessage:message style:WaitingViewShowStyleFullSelfView autoDissmissAfterDelay:interval finish:finish];
}

- (void)showMessage:(NSString *)message style:(WaitingViewShowStyle) style autoDissmissAfterDelay:(NSTimeInterval)interval finish:(void (^)())finish{
    if ([message length] == 0) {
        return;
    }
    else if ([message isEqualToString:NSURLErrorDomain]) {
        message = @"网络异常，请检查网络连接！";
    }
    
    //    if (self.navigationController.view == nil) {
    //        EXPORTLOG(DEBUG_DEBUG, @"view is nil");
    //        return;
    //    }
    MBProgressHUD *_msgHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //_msgHud.yOffset=-32;
    _msgHud.mode = MBProgressHUDModeText;
    _msgHud.detailsLabelText = message;
    if (style == WaitingViewShowStyleFullSelfView) {
        _msgHud.userInteractionEnabled = NO;
    }else{
        _msgHud.userInteractionEnabled = YES;
    }
    _msgHud.detailsLabelFont = [UIFont systemFontOfSize:14.0f];
    _msgHud.removeFromSuperViewOnHide = YES;
    if (interval == 0) {
        interval = 2;
    }
    [_msgHud hide:YES afterDelay:interval];
    if(finish != nil){
        [self performSelector:@selector(showMessageFinish:) withObject:finish afterDelay:interval];
    }
}

//Add:张如进 2013-07-19    增加finish调用
- (void)showMessageFinish:(void (^)())finish{
    finish();
}
//End

- (void)showWaitingViewWithMessage:(NSString *)message style:(WaitingViewShowStyle)style{
    @synchronized(self){
        _viewStyle = style;
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(didDismissWatingView) object:nil];
        [self performSelector:@selector(showWaitingViewInSelfView:) withObject:message afterDelay:0];
    }
}

- (void)showWaitingViewInSelfView:(NSString *)message{
    if (_viewStyle == WaitingViewShowStyleFullScreen) {
        if (_waitingView == nil) {
            _waitingView = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
        }
        _waitingView.yOffset = 0;
        [[[UIApplication sharedApplication].windows objectAtIndex:0] addSubview:_waitingView];
    }else{
        if (_waitingView == nil) {
            _waitingView = [[MBProgressHUD alloc] initWithView:self.view];
        }
        if (self.navigationController != nil && self.navigationController.navigationBarHidden == NO) {
            _waitingView.yOffset = - self.navigationController.navigationBar.frame.size.height;
        }
        [self.view addSubview:_waitingView];
    }
    
    _waitingView.mode = MBProgressHUDModeIndeterminate;
    
    if (message == nil) {
        message = @"请稍候…";
    }
    _waitingView.detailsLabelText = message;
    
    [_waitingView show:YES];
    
}
- (void)dismissWaitingView{
    if (_waitingView == nil) {
        [self performSelector:@selector(didDismissWatingView) withObject:nil afterDelay:0];
    }else {
        [self didDismissWatingView];
    }
}
- (void)dismissWaitingViewAfterDelay:(NSTimeInterval)interval{
    //    [_waitingView hide:YES afterDelay:interval];
    [self performSelector:@selector(didDismissWatingView) withObject:nil afterDelay:interval];
    //    if (_waitingView == nil) {
    //        [self performSelector:@selector(didDismissWatingView) withObject:nil afterDelay:interval];
    //    }else {
    //        [_waitingView dismissAfterDelay:interval];
    //        _waitingView = nil;
    //    }
}

- (void)didDismissWatingView{
    [_waitingView hide:YES];
    _waitingView = nil;
    //    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(didDismissWatingView) object:nil];
    //    [_waitingView dismiss];
    //    _waitingView = nil;
}

-(void)showHelp{
    [self showMessage:@"功能正在开发中..." autoDissmissAfterDelay:0];
}

- (void)showTitle:(NSString *)title message:(NSString *)message cancel:(NSString *)cancel autoDissmissAfterDelay:(NSTimeInterval)interval{
    
    if (self.view.superview == nil) {
        return;
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:cancel otherButtonTitles: nil];
    [alertView show];
    if (interval > 0) {
        [self performSelector:@selector(dismissAlertView:) withObject:alertView afterDelay:interval];
    }
}

- (void)dismissAlertView:(UIAlertView *)alertView{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
}
- (void)performBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay {
    [self performSelector:@selector(fireBlockAfterDelay:) withObject:block afterDelay:delay];
}


- (void)cancelPerformBlock:(void (^)(void))block {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(fireBlockAfterDelay:) object:block];
}
- (void)fireBlockAfterDelay:(void (^)(void))block {
    block();
}

-(UIImageView*)getBackImageView{
    UIImageView *backImageView = [UIImageView new];
    backImageView.backgroundColor = [UIColor whiteColor];
    backImageView.layer.cornerRadius = 5;
    backImageView.layer.borderWidth = 1;
    backImageView.layer.borderColor = DefaultLineColor.CGColor;
    return backImageView;
}

//-(void)postImageToQiNiu:(UIImage*)image complete:(QNUpCompletionHandler)completionHandler{
//    [HttpToolAction getQiNiuTokenActionWithBlock:^(id result, NSError *error){
//        [self postImageWithToken:result andImage:image complete:completionHandler];
//
//
//    }];
//
//}

//-(void)postImageWithToken:(NSString*)tokenString andImage:(UIImage*)image complete:(QNUpCompletionHandler)completionHandler{
//    NSString *token = tokenString;
//    QNUploadManager *upManager = [[QNUploadManager alloc] init];
//    NSData *data = UIImageJPEGRepresentation(image,0.5);
//    NSString *keyName = [NSProcessInfo processInfo].globallyUniqueString;
//    keyName = [NSString stringWithFormat:@"%@.png",keyName];
//    [upManager putData:data key:keyName token:token
//              complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
//                  //                  http://7xo1bg.com1.z0.glb.clouddn.com
//                  NSLog(@"%@", info);
//                  NSLog(@"%@", resp);
////                  NSString *keyString = [NSString stringWithFormat:@"http://7xo1bg.com1.z0.glb.clouddn.com/%@",key];
//                  if (completionHandler) {
//                      completionHandler(info,key,resp);
//                  }
//              } option:nil];
//}

//有序队列上传
//-(void)postListImageArray:(NSArray*)imageArray withBlock:(void(^)(NSArray *array)) block{
//    if (imageArray.count == 0) {
//        block(@[]);
//    }
//    dispatch_queue_t concurrentQueue = dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
//    NSMutableArray *mutableArray = [NSMutableArray array];
//    for (int i =0;i<imageArray.count;i++) {
//        UIImage *image = imageArray[i];
//        dispatch_async(concurrentQueue, ^(){
//            [HttpToolAction getQiNiuTokenActionWithBlock:^(id result, NSError *error) {
//                [self postImageWithToken:result andImage:image complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
//                    if (i == 0) {
//                        [mutableArray insertObject:key atIndex:0];
//
//                    }else{
//                        [mutableArray addObject:key];
//
//                    }
//                    if (mutableArray.count == imageArray.count) {
//                        if (block) {
//                            block(mutableArray);
//
//                        }
//                    }
//                }];
//            }];
//        });
//
//    }
//
//}



//-(BOOL)prefersStatusBarHidden{
//    return NO;
//}

-(void)showNoResult{
    if (_resultView == nil) {
        int height = SCREEN_HEIGHT-StatusBarHeight-44-TabBarHeight;
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
        UIImageView *noImageView = [UIImageView new];
        noImageView.image = [UIImage imageNamed:@"noresult"];
        [view addSubview:noImageView];
        noImageView.sd_layout.centerXEqualToView(view).centerYIs(height/2-40).widthIs(90).heightIs(90);
        
        UILabel *titleLabel = [UILabel new];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont systemFontOfSize:14];
        titleLabel.textColor = [UIColor grayColor];
        [view addSubview:titleLabel];
        titleLabel.sd_layout.centerXIs(SCREEN_WIDTH/2-5).centerYIs(height/2+20).widthIs(SCREEN_WIDTH).heightIs(20);
        titleLabel.text = @"目前没有数据";
        [self.view addSubview:view];
        _resultView = view;
    }
    
}

//-(void)showNoResultViewWithView:(UIView*)view{
//    UIImageView *noImageView = [UIImageView new];
//    noImageView.image = [UIImage imageNamed:@"noresult"];
//    [view addSubview:noImageView];
//    noImageView.sd_layout.centerXIs(SCREEN_WIDTH/2).centerYIs(view.height/2-40).widthIs(90).heightIs(90);
//    
//    UILabel *titleLabel = [UILabel new];
//    titleLabel.textAlignment = NSTextAlignmentCenter;
//    titleLabel.font = [UIFont systemFontOfSize:14];
//    titleLabel.textColor = [UIColor grayColor];
//    [view addSubview:titleLabel];
//    titleLabel.sd_layout.centerXIs(SCREEN_WIDTH/2-5).centerYIs(view.height/2+20).widthIs(SCREEN_WIDTH).heightIs(20);
//    titleLabel.text = @"目前没有数据";
//    
//}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

